/* $RCSFile: CreateCrmEntity.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/CreateCrmEntity/CreateCrmEntity.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:18  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:46  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:24  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;  
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Data.SqlClient;
using System.Web.Services.Protocols;
using System.Globalization;

using AddonNice.UI;
using AddonNice.Design;
using AddonNice.UI.WebControls;
using AddonNice.Security;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Settings;

using AddonNice.CRMWrapper;
using CrmSdk;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.CreateCrmEntity
{
	/// <summary>
    /// Initializer class for CreateCrmEntity 
    /// </summary>
    public class CreateCrmEntitySI : PortalCRMModuleControlSI
    {
        public CreateCrmEntitySI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CreateCrmEntitySI Ctor BEG.",ModuleTraceSwitch.Sw.Info);
            InitSettings(bSettings,pm);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CreateCrmEntitySI Ctor END.",ModuleTraceSwitch.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CreateCrmEntitySI InitSettings BEG.",ModuleTraceSwitch.Sw.Info);
            
            base.InitSettings(bSettings,pm);
        }
    }

    /// <summary>  
    ///	Create a Custom entity in CRM 4 (not available for CRM 3) using MetaDataBuilder
    /// </summary>
    public partial class CreateCrmEntity : PortalCRMModuleControl
    {

		/// <summary>
		/// Only 4
		/// </summary>
		public override VersionType ModuleType
		{
			get
			{
				return VersionType.CrmV4;
			}
		}

        public override bool AdminModule
        {
            get
            {
                return true;
            }
        }

        /// <summary>
        /// No entity needed here
        /// </summary>
        public override bool NeedAttachedEntity
        {
            get
            {
                return false;
            }
        }

        #region General implementation

        public override Guid GuidID
        {
            get
            {
                return new Guid("{CC0581B6-5C59-48b5-A5AE-A9D8F623036C}");
            }
        }
        #endregion General implementation


        DataTable TbAttributes
        {
            get
            {
                object obj      =   Session["AttributesData"];
                if (obj != null)
                {
                    return (DataTable)obj;
                }
                DataTable Tb    =   new DataTable("Attributes");
                DataColumn c    =   Tb.Columns.Add("Id", typeof(int));
                Tb.Columns.Add("SchemaName", typeof(string));
                Tb.Columns.Add("DisplayName", typeof(string));
                Tb.Columns.Add("DisplayColName", typeof(string));
                Tb.Columns.Add("AttributeType", typeof(int));
                Tb.Columns.Add("Description", typeof(string));
                Tb.Columns.Add("MaxLen", typeof(int));
                Tb.Columns.Add("MaxValue", typeof(int));
                Tb.Columns.Add("MinValue", typeof(int));
                Tb.Columns.Add("Precision", typeof(int));
                Tb.Columns.Add("TextFormat", typeof(int));
                Tb.Columns.Add("IntFormat", typeof(int));
                Tb.Columns.Add("DateFormat", typeof(int));
                Tb.Columns.Add("PickListOption", typeof(string));
                Tb.PrimaryKey   =   new DataColumn[] { c };

                Session["AttributesData"]   =   Tb;
                return Tb;
            }
        }

        protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridEditableItem )
            {
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity RadGrid1_ItemDataBound BEG Item: {0}, Type: {1}, IsInEditMode: {2}",
                        e.Item,e.Item.ItemType,e.Item.IsInEditMode),ModuleTraceSwitch.Sw.Info);
                GridEditableItem item       =   (GridEditableItem)e.Item;
                if ( item.IsInEditMode )
                {
                    DataRowView rw          =   null;
                    if ( !item.OwnerTableView.IsItemInserted )
                        rw                  =   (DataRowView)e.Item.DataItem;
                    int     nbexp           =   0;
                    RadComboBox rdcbx       =   null;
                    try
                    {  
                        rdcbx               =   (RadComboBox)item["AttributeType"].Controls[0];
                    }
                    catch
                    { 
                        rdcbx               =   null;
                        nbexp++;
                    }
                    if ( rdcbx != null )
                    {
                        rdcbx.Items.Clear();
                        rdcbx.Items.Add(new RadComboBoxItem("Boolean",((int)AttributeInternalType.Boolean).ToString()));
                        rdcbx.Items.Add(new RadComboBoxItem("DateTime",((int)AttributeInternalType.DateTime).ToString()));
                        rdcbx.Items.Add(new RadComboBoxItem("Decimal",((int)AttributeInternalType.Decimal).ToString()));
                        rdcbx.Items.Add(new RadComboBoxItem("Float",((int)AttributeInternalType.Float).ToString()));
                        rdcbx.Items.Add(new RadComboBoxItem("Integer",((int)AttributeInternalType.Integer).ToString()));
                        rdcbx.Items.Add(new RadComboBoxItem("Memo",((int)AttributeInternalType.Memo).ToString()));
                        rdcbx.Items.Add(new RadComboBoxItem("Money",((int)AttributeInternalType.Money).ToString()));
                        rdcbx.Items.Add(new RadComboBoxItem("Picklist",((int)AttributeInternalType.Picklist).ToString()));
                        RadComboBoxItem it0     =   new RadComboBoxItem("String",((int)AttributeInternalType.String).ToString());
                        rdcbx.Items.Add(it0);
                        if (rw != null)
                        {
                            RadComboBoxItem it  =   rdcbx.Items.FindItemByValue(rw["AttributeType"].ToString());
                            if (it != null)
                                it.Selected     =   true;
                        }
                        else it0.Selected       =   true;

                        if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity RadGrid1_ItemDataBound AttributeType Count: {0}",rdcbx.Items.Count),ModuleTraceSwitch.Sw.Info);
                    }
                    try
                    {  
                        rdcbx               = (RadComboBox)item["TextFormat"].Controls[0];
                    }
                    catch
                    { 
                        rdcbx               =   null;
                        nbexp++;
                    }
                    if (rdcbx != null)
                    {
                        rdcbx.Items.Clear();
                        rdcbx.Items.Add(new RadComboBoxItem("Email", ((int)StringInternalFormat.Email).ToString()));
                        rdcbx.Items.Add(new RadComboBoxItem("Text", ((int)StringInternalFormat.Text).ToString()));
                        rdcbx.Items.Add(new RadComboBoxItem("Url", ((int)StringInternalFormat.Url).ToString()));
                        rdcbx.Items.Add(new RadComboBoxItem("TickerSymbol", ((int)StringInternalFormat.TickerSymbol).ToString()));
                        rdcbx.Items.Add(new RadComboBoxItem("PhoneticGuide", ((int)StringInternalFormat.PhoneticGuide).ToString()));
                        if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity RadGrid1_ItemDataBound TextFormat Count: {0}", rdcbx.Items.Count), ModuleTraceSwitch.Sw.Info);
                        if (rw != null)
                        {
                            RadComboBoxItem it = rdcbx.Items.FindItemByValue(rw["TextFormat"].ToString());
                            if (it != null)
                                it.Selected = true;
                        }
                    }

                    try
                    {  
                        rdcbx               = (RadComboBox)item["IntFormat"].Controls[0];
                    }
                    catch
                    { 
                        rdcbx               =   null;
                        nbexp++;
                    }
                    if (rdcbx != null)
                    {
                        rdcbx.Items.Clear();
                        rdcbx.Items.Add(new RadComboBoxItem("None", ((int)IntegerInternalFormat.None).ToString()));
                        rdcbx.Items.Add(new RadComboBoxItem("Duration", ((int)IntegerInternalFormat.Duration).ToString()));
                        rdcbx.Items.Add(new RadComboBoxItem("TimeZone", ((int)IntegerInternalFormat.TimeZone).ToString()));
                        rdcbx.Items.Add(new RadComboBoxItem("Language", ((int)IntegerInternalFormat.Language).ToString()));
                        rdcbx.Items.Add(new RadComboBoxItem("Locale", ((int)IntegerInternalFormat.Locale).ToString()));
                        if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity RadGrid1_ItemDataBound IntFormat Count: {0}", rdcbx.Items.Count), ModuleTraceSwitch.Sw.Info);
                        if (rw != null)
                        {
                            RadComboBoxItem it = rdcbx.Items.FindItemByValue(rw["IntFormat"].ToString());
                            if (it != null)
                                it.Selected = true;
                        }
                    }
                    
                    try
                    {  
                        rdcbx               = (RadComboBox)item["DateFormat"].Controls[0];
                    }
                    catch
                    { 
                        rdcbx               =   null;
                    }
                    if (rdcbx != null)
                    {
                        rdcbx.Items.Clear();
                        rdcbx.Items.Add(new RadComboBoxItem("DateOnly", ((int)DateTimeInternalFormat.DateOnly).ToString()));
                        rdcbx.Items.Add(new RadComboBoxItem("DateAndTime", ((int)DateTimeInternalFormat.DateAndTime).ToString()));
                        if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity RadGrid1_ItemDataBound END DateFormat Count: {0}", rdcbx.Items.Count), ModuleTraceSwitch.Sw.Info);
                        if (rw != null)
                        {
                            RadComboBoxItem it = rdcbx.Items.FindItemByValue(rw["DateFormat"].ToString());
                            if (it != null)
                                it.Selected = true;
                        }
                    }
                    if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity RadGrid1_ItemDataBound END nbexp: {0}",nbexp),ModuleTraceSwitch.Sw.Info);
                }
                else
                {
                    if ( e.Item.ItemType != GridItemType.Item && 
                        e.Item.ItemType != GridItemType.AlternatingItem )
                        return;
                    DataRowView rw              =   (DataRowView)e.Item.DataItem;
                    int ival                    =   (int)rw["AttributeType"];
                    if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity RadGrid1_ItemDataBound AttributeType: {0}",ival),ModuleTraceSwitch.Sw.Info);
                    item["AttributeType"].Text  =   ((AttributeInternalType)ival).ToString();
                    ival                        =   (int)rw["TextFormat"];
                    if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity RadGrid1_ItemDataBound TextFormat: {0}",ival),ModuleTraceSwitch.Sw.Info);
                    item["TextFormat"].Text     =   ((StringInternalFormat)ival).ToString();
                    ival                        =   (int)rw["IntFormat"];
                    if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity RadGrid1_ItemDataBound IntFormat: {0}",ival),ModuleTraceSwitch.Sw.Info);
                    item["IntFormat"].Text      =   ((IntegerInternalFormat)ival).ToString();
                    ival                        =   (int)rw["DateFormat"];
                    if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity RadGrid1_ItemDataBound DateFormat: {0}",ival),ModuleTraceSwitch.Sw.Info);
                    item["DateFormat"].Text     =   ((DateTimeInternalFormat)ival).ToString();
                }
            }
        }  

        private void RadGrid1_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity RadGrid1_NeedDataSource BEG RebindReason: {0}",e.RebindReason),ModuleTraceSwitch.Sw.Info);
             RadGrid1.DataSource = TbAttributes;
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]CreateCrmEntity RadGrid1_NeedDataSource END.",ModuleTraceSwitch.Sw.Info);
        }

        private void RadGrid1_InsertCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity RadGrid1_InsertCommand BEG e.Item : {0}", e.Item), ModuleTraceSwitch.Sw.Info);
            GridEditableItem editedItem     =   e.Item as GridEditableItem;
            DataTable attTable              =   TbAttributes;

            DataRow newRow                  =   attTable.NewRow();

            //a new primary key value should be generated
            DataRow[] allValues             =   attTable.Select(string.Empty, "Id", DataViewRowState.CurrentRows);
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity RadGrid1_InsertCommand allValues.Length: {0}", allValues.Length), ModuleTraceSwitch.Sw.Info);
            if (allValues.Length > 0)
            {
                newRow["Id"]                =   (int)allValues[allValues.Length - 1]["Id"] + 1;
            }
            else
            {
                newRow["Id"]                =   1; //the table is empty;
            }

            //Set new values
            Hashtable newValues             =   new Hashtable();
            //The GridTableView will fill the values from all editable columns in the hash
            e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);

            try
            {
                foreach (DictionaryEntry entry in newValues)
                {
                    object ob   =   entry.Value;
                    if (ob != null)
                    {
                        newRow[(string)entry.Key] = ob;
                        if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity RadGrid1_InsertCommand inserting field: {0}, Value: {1}", entry.Key, entry.Value), ModuleTraceSwitch.Sw.Info);
                    }
                }
            }
            catch (Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CreateCrmEntity RadGrid1_InsertCommand ex: {0}", ex), ModuleTraceSwitch.Sw.Info);
                LbError.Text += "Unable to insert into Attributes. Reason: " + ex.Message;
                e.Canceled = true;
            }

            attTable.Rows.Add(newRow);
            string msg  =   string.Format("Attribute {0} inserted",newRow["Id"]);
            RadGrid1.Controls.Add(new LiteralControl(msg));
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CreateCrmEntity RadGrid1_InsertCommand END "+msg, ModuleTraceSwitch.Sw.Info);
        }

        protected void RadGrid1_UpdateCommand(object source, GridCommandEventArgs e)
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity RadGrid1_UpdateCommand BEG e.Item : {0}",e.Item),ModuleTraceSwitch.Sw.Info);
            GridEditableItem editedItem     =   e.Item as GridEditableItem;
            DataTable attTable              =   TbAttributes;
            string strReq                   =   "Id = " + editedItem.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["Id"].ToString();
            //Locate the changed row in the DataSource
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity RadGrid1_UpdateCommand Request: {0}",strReq),ModuleTraceSwitch.Sw.Info);

            DataRow[] changedRows           =   attTable.Select(strReq);
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity RadGrid1_UpdateCommand changedRows.Length: {0}",changedRows.Length),ModuleTraceSwitch.Sw.Info);

            if (changedRows.Length != 1)
            {
                RadGrid1.Controls.Add(new LiteralControl("Unable to locate the Order for updating."));
                e.Canceled = true;
                return;
            }

            //Update new values
            Hashtable newValues         =   new Hashtable();
            //The GridTableView will fill the values from all editable columns in the hash
            e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);

            DataRow changedRow          =   changedRows[0];
            changedRow.BeginEdit();
            try
            {
                foreach (DictionaryEntry entry in newValues)
                {
                    object ob = entry.Value;
                    if (ob != null)
                    {
                        changedRow[(string)entry.Key] = entry.Value;
                        if (ModuleTraceSwitch.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity RadGrid1_UpdateCommand updating field: {0}, Value: {1}", entry.Key, entry.Value), ModuleTraceSwitch.Sw.Info);
                    }
                }
                changedRow.EndEdit();
            }
            catch (Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CreateCrmEntity RadGrid1_UpdateCommand ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
                changedRow.CancelEdit();
                RadGrid1.Controls.Add(new LiteralControl("Unable to update Orders. Reason: " + ex.Message));
                e.Canceled = true;
            }

            attTable.AcceptChanges();

            string msg  =   string.Format("Attribute {0} updated",changedRow["Id"]);
            RadGrid1.Controls.Add(new LiteralControl(msg));
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]CreateCrmEntity RadGrid1_UpdateCommand END "+msg,ModuleTraceSwitch.Sw.Info);
        }
        
        
        protected void RadGrid1_DeleteCommand(object source, GridCommandEventArgs e)
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]CreateCrmEntity RadGrid1_DeleteCommand BEG.",ModuleTraceSwitch.Sw.Info);
            int ID              =   (int)(e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["Id"];
            DataTable attTable  =   TbAttributes;
            if (attTable.Rows.Find(ID) != null)
            {
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity RadGrid1_DeleteCommand Id: {0}",ID),ModuleTraceSwitch.Sw.Info);
                attTable.Rows.Find(ID).Delete();
                attTable.AcceptChanges();
            }
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( "[V]CreateCrmEntity RadGrid1_DeleteCommand END.",ModuleTraceSwitch.Sw.Info);
        }
        
        // ?????
        protected void RadGrid1_PreRender(object sender, System.EventArgs e)
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity RadGrid1_PreRender BEG IsPostBack: {0}",IsPostBack),ModuleTraceSwitch.Sw.Info);
            if ( !IsPostBack )
            {
                RadGrid1.EditIndexes.Add(1);
                RadGrid1.MasterTableView.Rebind();
            }
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CreateCrmEntity RadGrid1_PreRender END.",ModuleTraceSwitch.Sw.Info);
        }
        
        /// <summary>
        /// Ctor
        /// </summary>
        public CreateCrmEntity()
        {
            // Validators : name Ok
            ValidationGroup         =   "Main";
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity Page_Load BEG IsPostBack: {0}",IsPostBack),ModuleTraceSwitch.Sw.Info);
            if (!IsPostBack)
            {
            }
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity Page_Load END IsPostBack: {0}",IsPostBack),ModuleTraceSwitch.Sw.Info);
        }

        /// <summary>
        /// Use EntityBuilder to Build entity
        /// </summary>
        void CreateCrmEntity_ADNUpdateModule(object sender, ModuleEventArgs e)
        {
            if (!Page.IsValid)
            {
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( "[V]CreateCrmEntity CreateCrmEntity_ADNUpdateModule : Page not valid",ModuleTraceSwitch.Sw.Info);
                e.Cancel            =   true;
                return;
            }
            try
            {
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity CreateCrmEntity_ADNUpdateModule BEG Build Entity: {0}",RbCreate.Items[0].Selected),ModuleTraceSwitch.Sw.Info);
                MetaDataBuilder mb              =   ReadData();
                mb.Build((CrmWrapper4)Wrapper,RbCreate.Items[0].Selected,true);
                PnSummary.Controls.Add(new LiteralControl(mb.Result));
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity CreateCrmEntity_ADNUpdateModule END LbAttributeId: {0}, EntityID:{1}, Count: {2}",
                        mb.eBuilder.AttributeId,mb.eBuilder.EntityID,mb.attList.Count),ModuleTraceSwitch.Sw.Info);
                // to avoid  a second click
                updateBtn.Enabled   =   false; 
                // To allow adding attributes by returning on previous tabs
                CBList.Items[1].Selected    =   true;
            }
           catch (SoapException sex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CreateCrmEntity CreateCrmEntity_ADNUpdateModule soap ex :{0}", sex), ModuleTraceSwitch.Sw.Info);
                StringBuilder sb                =   new StringBuilder();
                sb.AppendFormat("Error: <br />{0}<br />",sex.Detail.InnerText);
                PnSummary.Controls.Add(new LiteralControl(sb.ToString()));
                e.Cancel            =   true;
                return;
            }
           catch (Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CreateCrmEntity CreateCrmEntity_ADNUpdateModule ex :{0}", ex), ModuleTraceSwitch.Sw.Info);
                StringBuilder sb                =   new StringBuilder();
                sb.AppendFormat("Error: <br />{0}<br />",ex);
                PnSummary.Controls.Add(new LiteralControl(sb.ToString()));
                e.Cancel            =   true;
                return;
            }
        }

        MetaDataBuilder ReadData()
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]CreateCrmEntity ReadData BEG.", ModuleTraceSwitch.Sw.Info);
            MetaDataBuilder mb                  =   null;
            PnSummary.Controls.Clear();
            try
            {
                string entitySchemaName         =   TbSchemaName.Text.Trim();
                EntityBuilder bu                =   new EntityBuilder(entitySchemaName);
                bu.DisplayName                  =   TbDisplayName.Text.Trim();
                bu.DisplayCollectionName        =   TbDisplayCollectionName.Text.Trim();
                bu.Description                  =   TbDescription.Text.Trim();
                bu.HasActivities                =   CBList.Items[0].Selected;
                bu.HasNotes                     =   CBList.Items[1].Selected;
                bu.PrimaryFieldName             =   TbPrimaryFieldName.Text.Trim();
                bu.PrimaryFieldDisplayName      =   TbPrimaryFieldDisplayName.Text.Trim();
                if ( TbMaxLength.Value.HasValue )
                    bu.MaxLength                =   (int)TbMaxLength.Value.Value;
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity ReadData before Build Schema: {0}, DisplayName: {1}, DisplayCollectionName: {2}, Description: {3}, HasActivities: {4}, HasNotes: {5},"+
                        " PrimaryFieldName: {6}, PrimaryFieldDisplayName: {7}, MaxLength: {8}", 
                        new object[]{bu.SchemaName,bu.DisplayName,bu.DisplayCollectionName,bu.Description,bu.HasActivities,bu.HasNotes,
                        bu.PrimaryFieldName,bu.PrimaryFieldDisplayName,bu.MaxLength}), ModuleTraceSwitch.Sw.Info);
                List<AttributeBuilder> attList  =   new List<AttributeBuilder>();
                DataTable tb                    =   TbAttributes;
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity ReadData TbAttributes Count: {0}.",tb.Rows.Count),ModuleTraceSwitch.Sw.Info);
                for (int i = 0; i < tb.Rows.Count; i++)
                {
                    DataRow rw                  =   tb.Rows[i];
                    AttributeInternalType tp    =   (AttributeInternalType)(int)rw["AttributeType"];
                    AttributeBuilder ab         =   null;
                    string strBlt               =   string.Empty;
                    if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity ReadData Adding Attribute Type: {0}.",tp),ModuleTraceSwitch.Sw.Info);
                    string attSchemaName        =   ((string)rw["SchemaName"]).Trim();
                    switch (tp)
                    {
                        case AttributeInternalType.String:
                            ab = new StringAttributeBuilder(entitySchemaName, attSchemaName);
                            ab.MaxLength        = (int)rw["MaxLen"];
                            ab.TextFormat       = (StringInternalFormat)(int)rw["TextFormat"];
                            if (ModuleTraceSwitch.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity ReadData Attribute String, Format: {0}, Max length: {1}",ab.TextFormat,ab.MaxLength), ModuleTraceSwitch.Sw.Info);
                            break;
                        case AttributeInternalType.Memo:
                            ab = new MemoAttributeBuilder(entitySchemaName, attSchemaName);
                            ab.MaxLength        = (int)rw["MaxLen"];
                            if (ModuleTraceSwitch.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity ReadData Attribute Memo, Format: {0}, Max length: {1}",ab.TextFormat,ab.MaxLength), ModuleTraceSwitch.Sw.Info);
                            break;
                        case AttributeInternalType.Integer:
                            ab = new IntegerAttributeBuilder(entitySchemaName, attSchemaName);
                            ab.MaxValue         = (int)rw["MaxValue"];
                            ab.MinValue         = (int)rw["MinValue"];
                            ab.IntFormat        = (IntegerInternalFormat)(int)rw["IntFormat"];
                            if (ModuleTraceSwitch.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity ReadData Attribute Integer, Format: {0}, Max value: {1}, Min value: {2}",ab.TextFormat,ab.MaxValue,ab.MinValue), ModuleTraceSwitch.Sw.Info);
                            break;
                        case AttributeInternalType.Money:
                            ab = new MoneyAttributeBuilder(entitySchemaName, attSchemaName);
                            ab.MaxMoneyValue    = (double)(int)rw["MaxValue"];
                            ab.MinMoneyValue    = (double)(int)rw["MinValue"];
                            ab.Precision        = (int)rw["Precision"];
                            if (ModuleTraceSwitch.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity ReadData Attribute Money, Max value: {0}, Min value: {1}, Precision: {2}",ab.MaxMoneyValue,ab.MinMoneyValue,ab.Precision), ModuleTraceSwitch.Sw.Info);
                            break;
                        case AttributeInternalType.DateTime:
                            ab = new DateTimeAttributeBuilder(entitySchemaName, attSchemaName);
                            ab.DateFormat       = (DateTimeInternalFormat)(int)rw["DateFormat"];
                            if (ModuleTraceSwitch.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity ReadData Attribute DateTime, Format: {0}",ab.DateFormat), ModuleTraceSwitch.Sw.Info);
                            break;
                        case AttributeInternalType.Decimal:
                            ab = new DecimalAttributeBuilder(entitySchemaName, attSchemaName);
                            ab.MaxMoneyValue    = (double)(int)rw["MaxValue"];
                            ab.MinMoneyValue    = (double)(int)rw["MinValue"];
                            ab.Precision        = (int)rw["Precision"];
                            if (ModuleTraceSwitch.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity ReadData Attribute Decimal, Max value: {0}, Min value: {1}, Precision: {2}",ab.MaxMoneyValue,ab.MinMoneyValue,ab.Precision), ModuleTraceSwitch.Sw.Info);
                            break;
                        case AttributeInternalType.Float:
                            ab = new FloatAttributeBuilder(entitySchemaName, attSchemaName);
                            ab.MaxMoneyValue    = (double)(int)rw["MaxValue"];
                            ab.MinMoneyValue    = (double)(int)rw["MinValue"];
                            ab.Precision        = (int)rw["Precision"];
                            if (ModuleTraceSwitch.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity ReadData Attribute Float, Max value: {0}, Min value: {1}, Precision: {2}",ab.MaxMoneyValue,ab.MinMoneyValue,ab.Precision), ModuleTraceSwitch.Sw.Info);
                            break;
                        case AttributeInternalType.Boolean:
                            ab = new BoolAttributeBuilder(entitySchemaName, attSchemaName);
                            if (ModuleTraceSwitch.Sw.TraceVerbose)
                                Trace2.WriteLine("[V]CreateCrmEntity ReadData Attribute Bool", ModuleTraceSwitch.Sw.Info);
                            break;
                        case AttributeInternalType.Picklist:
                            ab = new PickListAttributeBuilder(entitySchemaName, attSchemaName);
                            string[] opt    =   ((string)rw["PickListOption"]).Split(new []{','},StringSplitOptions.RemoveEmptyEntries);
                            ab.PickListOptions  =  opt;
                            if (ModuleTraceSwitch.Sw.TraceVerbose)
                                Trace2.WriteLine("[V]CreateCrmEntity ReadData Attribute PickList", ModuleTraceSwitch.Sw.Info);
                            break;
                        default:
                            continue;
                    }
                    ab.DisplayName              = rw["DisplayName"].ToString().Trim();
                    ab.DisplayCollectionName    = rw["DisplayColName"].ToString().Trim();// no DisplayCollectionName ??
                    ab.Description              = rw["Description"].ToString().Trim();
                    if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity ReadData Display Name: {0}, Display collection Name: {1}, Description: {2}",ab.DisplayName,ab.DisplayCollectionName,ab.Description), ModuleTraceSwitch.Sw.Info);
                    if (ModuleTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity ReadData Building attribute: {0}, Type: {1}.",ab.SchemaName,ab.AttType),ModuleTraceSwitch.Sw.Info);
                    attList.Add(ab);
                }
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity ReadData Metadatabuilder attList.count: {0}.",attList.Count),ModuleTraceSwitch.Sw.Info);
                mb                              =   new MetaDataBuilder(bu,attList);
                string result                   =   mb.Prepare((CrmWrapper4)Wrapper,true);
                PnSummary.Controls.Add(new LiteralControl(result));
                // enable update button if conditions Ok: create entity or attlist filled
                if ( !updateBtn.Enabled && 
                    ( CBList.Items[0].Selected || (attList.Count > 0 ) ) )
                    updateBtn.Enabled = true;
                if (ModuleTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity ReadData after Prepare Summary: {0}.",result),ModuleTraceSwitch.Sw.Info);
            }
            catch (SoapException sex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CreateCrmEntity ReadData soap ex :{0}", sex), ModuleTraceSwitch.Sw.Info);
                PnSummary.Controls.Add(new LiteralControl(sex.Detail.InnerText));
            }
            catch (Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CreateCrmEntity ReadData ex :{0}", ex), ModuleTraceSwitch.Sw.Info);
                throw;
            }
            return mb;
        }

        
        void RadTabStrip1_TabClick(object sender, RadTabStripEventArgs e)
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity RadTabStrip1_TabClick  BEG TabIndex: {0}.",e.Tab.TabIndex),ModuleTraceSwitch.Sw.Info);
            if ( e.Tab.TabIndex != 2 )
                return;
            ReadData();
        }


        /// <summary>
        /// Reset all values
        /// </summary>
        void ResetBtn_Click(object sender, ImageClickEventArgs e)
        {
            TbSchemaName.Text       =   string.Empty;
            TbDisplayName.Text      =   string.Empty;
            TbDisplayCollectionName.Text=   string.Empty;
            TbDescription.Text          =   string.Empty;
            CBList.Items[0].Selected    =   true;
            CBList.Items[1].Selected    =   true;
            TbPrimaryFieldName.Text     =   string.Empty;
            TbPrimaryFieldDisplayName.Text  =   string.Empty;
            TbMaxLength.Text            =   string.Empty;
            PnSummary.Controls.Clear();
			RadTab Tab                  =   RadTabStrip1.Tabs[0];
			Tab.Enabled                 =   true;
			Tab.Selected                =   true;
            RadPageView PageView        =   RadMultiPage1.PageViews[0];
			PageView.Selected           =   true;
			Tab                         =   RadTabStrip1.Tabs[1];
			Tab.Enabled                 =   false;
			Tab                         =   RadTabStrip1.Tabs[2];
			Tab.Enabled                 =   false;
            Session["AttributesData"]   =   null;
            RadGrid1.Rebind();
        }

        void BtnNext_Click(object sender, ImageClickEventArgs e)
        {
            int idx                 =   RadTabStrip1.SelectedIndex;
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity BtnNext_Click  BEG TabIndex: {0}.",idx),ModuleTraceSwitch.Sw.Info);
			RadTab Tab              =   RadTabStrip1.Tabs[idx+1];
			Tab.Enabled             =   true;
			Tab.Selected            =   true;
            RadPageView PageView    =   RadMultiPage1.PageViews[idx+1];
			PageView.Selected       =   true;
            if ( Tab.Index == 2 )
                ReadData();
            if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CreateCrmEntity BtnNext_Click  END New Tab Index: {0}.",Tab.Index),ModuleTraceSwitch.Sw.Info);
		}

        #region Std overrides

        /// <summary>
        /// Triggered from Page.OnPreInit
        /// We must set the Add button before buttons are initialized by base method
        /// </summary>
        public override void Page_PreInit(object sender, EventArgs e)
        {
            base.Page_PreInit(sender, e);
            string strcult      =   Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
            updateBtn.SkinID    =   "Update_" + strcult;
            ResetBtn.SkinID     =   "Reset_" + strcult;
            BtnNext.SkinID      =   "setupnext_" + strcult;
            BtnNext2.SkinID     =   "setupnext_" + strcult;
        }

        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            Load                    +=  new System.EventHandler(this.Page_Load);
            ADNUpdateModule         +=  new PortalModuleEventHandler(CreateCrmEntity_ADNUpdateModule);
            ResetBtn.Click          +=  new ImageClickEventHandler(ResetBtn_Click);
            RadGrid1.PreRender      +=  new EventHandler(RadGrid1_PreRender);
            RadGrid1.NeedDataSource +=  new GridNeedDataSourceEventHandler(RadGrid1_NeedDataSource);
            RadGrid1.InsertCommand  +=  new GridCommandEventHandler(RadGrid1_InsertCommand);
            RadGrid1.UpdateCommand  +=  new GridCommandEventHandler(RadGrid1_UpdateCommand);
            RadGrid1.DeleteCommand  +=  new GridCommandEventHandler(RadGrid1_DeleteCommand);
            RadGrid1.ItemDataBound  +=  new GridItemEventHandler(RadGrid1_ItemDataBound);
            RadTabStrip1.TabClick   +=  new RadTabStripEventHandler(RadTabStrip1_TabClick);
            BtnNext.Click           +=  new ImageClickEventHandler(BtnNext_Click);
            BtnNext2.Click          +=  new ImageClickEventHandler(BtnNext_Click);
        }

        #endregion
    }
}
